package com.sw.rpc.service.zk;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.data.Stat;

/**
 * 服务器实例注册
 */
public class ServiceInstanceService {
    /**
     * 定义服务器注册的根节点信息
     */
    public static final String SERVERINSTANCEURL="/sw";
    public static final String ZK_SERVER="localhost:2181";
    /**
     * session
     */
    public static final int  SESSIONTIMEOUTMS=5000;
    /**
     * 链接等待
     */
    public static final int CONNECTIONTIMEOUTMS=3000;
    public  static ZkClient client;


    /**
     * 创建
     * @return
     */
    public static ZkClient createCuratorZookeeperClient(){
        if(null==client) {
            client=new ZkClient(ZK_SERVER);
            /**
             * 初始化服务根节点信息(持久化)
             */
            boolean exists = client.exists(SERVERINSTANCEURL);
            if(!exists){
                client.createPersistent(SERVERINSTANCEURL);
            }
        }
        return client;
    }

    /**
     * 创建节点信息
     * @param path 创建的路径
     * @return 被创建路径
     */
    public static void createPath(String path,ZkNodeData zkNodeData) throws Exception {
        path=SERVERINSTANCEURL+"/"+path;
        if(!client.exists(path)){
            client.createEphemeral(path,zkNodeData);
        }
    }

    /**
     * 返回数据
     * @param path
     * @return
     */
    public static ZkNodeData getZKNodeData(String path){
        path=SERVERINSTANCEURL+"/"+path;
        return (ZkNodeData) client.readData(path);
    }

    /**
     * 更新数据
     * @param path
     * @param zkNodeData
     * @return
     */
    public static Long updateZKNoData(String path,ZkNodeData zkNodeData){
        path=SERVERINSTANCEURL+"/"+path;
        Stat stat = client.writeData(path, zkNodeData);
        return stat.getCzxid();
    }

}
